"""
Copyright (c) 2012, Nimar S. Arora, nimar.arora@gmail.com
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.
    
    Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""
import sys
import struct
import StringIO
import time
import zlib
from optparse import OptionParser

TRIG_VALUES_PER_SEC = 10

# GMPEAK
# type = 'G'

# TRIGGER: class EWTrigger
# type='T', source, id, station, channel, network, location, lat, lon, time

# TRIGPARAMS : class TriggerParams
# type='P', source, id, num_params, compressed, trig_params[num_params]
# trig params
# station, channel, network, location, lat, lon, time, trigsec, trigusec,latency
# 1 .. 10:
#    float t;    // Predominant period value
#    float tsnr; // Predominant period snr
#    int ttime;  // Predominant period time - trigger_time in usecs
#    float d;	// Displacement value
#    float dsnr; // Displacement snr
#    int dtime;  // Displacement time - trigger_time in usecs
#    float v;	// Velocity value
#    float vsnr; // Velocity snr
#    int vtime;  // Velocity time - trigger_time in usecs
#    float a;	// Acceleration value
#    float asnr; // Acceleration snr
#    int atime;  // Acceleration time - trigger_time in usecs



# EWDATA
# type = 'D'

# EWTOGDATA
# type = 'O'

# sta, chan, net, loc, lat, lon, pktsec, pktusec
def parse_sta_hdr(pktstr):
  sta, = struct.unpack("5s", pktstr.read(5))
  sta = sta.rstrip('\x00')
  chan, = struct.unpack("4s", pktstr.read(4))
  chan = chan.rstrip('\x00')
  net, = struct.unpack("3s", pktstr.read(3))
  net = net.rstrip('\x00')
  loc, = struct.unpack("3s", pktstr.read(3))
  loc = loc.rstrip('\x00')
  lat, = struct.unpack("!d", pktstr.read(8))
  lon, = struct.unpack("!d", pktstr.read(8))

  pktsec, pktusec = struct.unpack("!ii", pktstr.read(8))
  return sta, chan, net, loc, lat, lon, pktsec, pktusec

def parse_packet(pkttxt):
  pktstr = StringIO.StringIO(pkttxt)
  
  pkttyp = pktstr.read(1)
  pktsrc = pktstr.read(1)
  pktid, = struct.unpack("!i", pktstr.read(4))
  
  # trigger
  if pkttyp == "T":
    sta, chan, net, loc, lat, lon, pktsec, pktusec = parse_sta_hdr(pktstr)
    pkttimetuple = time.gmtime(pktsec)
    pkt = (pkttyp, pktsrc, pktid, sta, chan, net, loc, lat, lon,
           pkttimetuple, pktusec)

  # trigger parameters
  elif pkttyp == 'P':
    num_params, = struct.unpack("!i", pktstr.read(4))
    iscompressed = bool(ord(pktstr.read(1)))
    if iscompressed:
      compressed_params = pktstr.read()
      uncompressed_params = zlib.decompress(compressed_params)
      pktstr = StringIO.StringIO(uncompressed_params)
    params = []
    for pnum in xrange(num_params):
      sta, chan, net, loc, lat, lon, trigsec, trigusec = parse_sta_hdr(pktstr)
      triglatency, = struct.unpack("!f", pktstr.read(4))
      trigvalues = []
      params.append((sta, chan, net, loc, lat, lon, trigsec, trigusec,
                     triglatency, trigvalues))
      for i in xrange(TRIG_VALUES_PER_SEC):
        t, tsnr, ttime = struct.unpack("!ffi", pktstr.read(12))
        d, dsnr, dtime = struct.unpack("!ffi", pktstr.read(12))
        v, vsnr, vtime = struct.unpack("!ffi", pktstr.read(12))
        a, asnr, atime = struct.unpack("!ffi", pktstr.read(12))

        trigvalues.append((t, tsnr, ttime, d, dsnr, dtime, v, vsnr, vtime,
                           a, asnr, atime))

    pkt = (pkttyp, pktsrc, pktid, params)
    
  else:
    print "Error: unhandled packet type", pkttyp
    sys.exit(2)
  
  if len(pktstr.read()):
    print "Error: unhandled extra bytes in trigger packet"
    sys.exit(2)

  return pkt

def read_trig_file(trig_fname):
  trigfile = open(trig_fname, "rb")

  while True:
    sizestr = trigfile.read(4)
    if len(sizestr) != 4:
      break
    size, = struct.unpack("!i", sizestr)
    pkttxt = trigfile.read(size)
    pkt = parse_packet(pkttxt)
    yield pkt
  
  trigfile.close()

def print_packet(pkt):
  pkttyp, pktsrc, pktid = pkt[:3]
  print "Type:", pkttyp, "Source:", pktsrc, "ID:", pktid

  if pkttyp == "T":
    (sta, chan, net, loc, lat, lon, pkttimetuple, pktusec) = pkt[3:]
    print sta, chan, net, loc, lat, lon,
    print time.strftime("%Y-%m-%d %H:%M:%S", pkttimetuple)+"."+str(pktusec)

  elif pkttyp == "P":
    params = pkt[3]
    for (sta, chan, net, loc, lat, lon, trigsec, trigusec,
         triglatency, trigvalues) in params:
      trigtimetuple = time.gmtime(trigsec)
      print sta, chan, net, loc, lat, lon,
      print time.strftime("%Y-%m-%d %H:%M:%S", trigtimetuple)+"."+str(trigusec),
      print triglatency
      print " T  TSNR  TTIME    D    DSNR  DTIME   V     VSNR  VTIME    A   ASNR  ATIME"
      for (t, tsnr, ttime, d, dsnr, dtime, v, vsnr, vtime,
           a, asnr, atime) in trigvalues:
        print "%.1f %.2f %7d %+1.1g %2.2f %7d %+1.1g %2.2f %7d %+1.1g %2.2f %7d"\
              % (t, tsnr, ttime, d, dsnr, dtime, v, vsnr, vtime, a, asnr, atime)
        
  
def main():
  parser = OptionParser()
  parser.set_usage("python print_triggers.py [options] <trigger-file>")
  (options, args) = parser.parse_args()
  
  if len(args) != 1:
    parser.print_usage()
    sys.exit(1)

  trig_fname = args[0]

  for pkt in read_trig_file(trig_fname):
    print_packet(pkt)


if __name__ == "__main__":
  main()
  
